package com.kx.config;

import com.kx.shiro.cache.RedisCacheManager;
import com.kx.shiro.realm.CustomRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来整合shiro相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1、创建shiroFilter
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String, String> map = new HashMap<>();
//        map.put("/index.jsp", "authc");  //authc：请求这个资源需要认证和授权
        map.put("/user/login", "anon");   //anon：设置为公共资源
        map.put("/user/register", "anon");
        map.put("/register.jsp", "anon");
        map.put("/**", "authc"); //使用通配符**，表示除login以外所有页面都需要认证授权
        //默认认证界面路径("login.jsp"可省略)
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    //2、创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        securityManager.setRealm(realm);
        return securityManager;
    }

    //3、创建自定义realm
    @Bean
    public Realm getRealm() {
        CustomRealm customRealm = new CustomRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(credentialsMatcher);
        customRealm.setCacheManager(new RedisCacheManager());
        customRealm.setCachingEnabled(true);    //开启全局缓存
        customRealm.setAuthenticationCachingEnabled(true);  //开启认证缓存
        customRealm.setAuthenticationCacheName("authenticationCache");
        customRealm.setAuthorizationCachingEnabled(true);   //开启授权缓存
        customRealm.setAuthorizationCacheName("authorizationCache");

        return customRealm;
    }
}
